﻿using System;
using System.Web.UI;
using CuoiHoi.Business;
using CuoiHoi.Entities;

namespace CuoiHoi.Admin
{
    public partial class login : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {   
            if (Request.Cookies["userName"] != null && Request.Cookies["pass"] != null)
            {
                cbNhoMatKhau.Checked = true;
                try
                {
                    DangNhap(Request.Cookies["userName"].Value, Request.Cookies["pass"].Value);
                }
                catch 
                {}              
            }
        }

        void ThongBao(string Loi)
        {
            ScriptManager.RegisterClientScriptBlock(this, GetType(), "Thông báo!", "<script>alert('" + Loi + "')</script>", false);
        }
        protected void btDangNhap_Click(object sender, EventArgs e)
        {
            // Ma hoa MD5 mat khau
            DangNhap(txtTenDangNhap.Text, Router.MaHoaMD5(txtMatKhau.Text));
        }

        void DangNhap(string TenDN,string Matkhau)
        {
            ENhanVien nhanvien = BNhanVien.DangNhap(TenDN, Matkhau);
     
            if (nhanvien.TenNhanVien==null)
            {

                ThongBao("Tài khoản hoặc mật khẩu sai....!");
            }
            else
            {
                if (cbNhoMatKhau.Checked == true)
                {
                    Response.Cookies["userName"].Value = TenDN;
                    Response.Cookies["pass"].Value = nhanvien.MatKhau;
 
                    Response.Cookies["userName"].Expires = DateTime.Now.AddDays(15);
                    Response.Cookies["pass"].Expires = DateTime.Now.AddDays(15);

                }
                else if (cbNhoMatKhau.Checked == false)
                {
                    Response.Cookies["pass"].Expires = DateTime.Now;
                    Response.Cookies["userName"].Expires = DateTime.Now;
                }

                Session["QuyenDN"] = nhanvien.idChucVu;
                Session["TenNV"] = nhanvien.TenNhanVien;                
                Session["Anh"] =nhanvien.AnhDaiDien;
                Session["idNhanVien"] = nhanvien.idNhanVien;
                Session["idChucVu"] = nhanvien.idChucVu;
                Response.Redirect("~/Admin/Default.aspx");
            }            
        }
    }
}